﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MvcEngine.Mvc.Models.ViewModels;
using MvcEngine.Blog.Helper;
using MvcEngine.Mvc.Extensions;
using MvcEngine.Blog.Components.Extensions;
using MvcEngine.Blog.Models.Entities;
using MvcEngine.Blog.Managers;
using MvcEngine.Core.Exceptions;
using MvcEngine.Core;

namespace MvcEngine.Blog.BackOffice.Filters
{
    public class BlogActionFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {

        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            BlogData blog = null;
            string blogName = (string)filterContext.RequestContext.RouteData.Values["blogName"];
            if (!string.IsNullOrEmpty(blogName)) 
            {
                blog = BlogManager.Current.GetBlog(blogName);
            }

            if (filterContext.RequestContext.RouteData.Values["blogId"] != null)
            {
                string blogId = filterContext.RequestContext.RouteData.Values["blogId"].ToString();
                if (!string.IsNullOrEmpty(blogId))
                {
                    blog = BlogManager.Current.GetBlog(new Guid(blogId));
                }
            }

            if (blog != null)
            {
                filterContext.ActionParameters["blogId"] = blog.Id;
                filterContext.ActionParameters["blogName"] = blog.Name;
                filterContext.RequestContext.RouteData.Values["blogId"] = blog.Id;
                filterContext.RequestContext.RouteData.Values["blogName"] = blog.Name;
            }
        }
    }
}
